(function(){
    function Snake(){
    this.direction = 'right';
    this.width = window.blockSize + 'px';
    this.height = window.blockSize + 'px';
    this.bodys = [ 
        {x:2,y:0,color:'blue'},
        {x:1,y:0,color:'yellow'},
        {x:0,y:0,color:'yellow'},
    ];
    }
    var snakeElements = [];

    function removeElements(){
        for(var i = snakeElements.length - 1; i >= 0; i--){
            window.map.removeChild(snakeElements[i]);
            snakeElements.splice(i,1);
        }
    }

    Snake.prototype.render = function(){
        removeElements();
        for(var i = 0;i < this.bodys.length-1; i++){
            var bodyItem = this.bodys[i];
            var div =document.createElement('div');
            window.map.appendChild(div);
            snakeElements.push(div);
            with(div.style){
                width = this.width;
                height = this.height;
                background = bodyItem.color;
                position = 'absolute';
                left =bodyItem.x * window.blockSize + 'px';
                top =bodyItem.y * window.blockSize + 'px';
            }
        }
    }
    //direction
    Snake.prototype.move = function (food){
        for(var i=this.bodys.length - 1; i>0; i--){
            this.bodys[i]['x'] =this.bodys[i-1]['x'];
            this.bodys[i]['y'] =this.bodys[i-1]['y'];
        }
        var head = this.bodys[0];
        switch(this.direction){
            case 'left':
                head.x --;
                break;
            case 'right':
                head.x ++;
                break;
            case 'up':
                head.y --;
                break;
            case 'down':
                head.y ++;
                break;
        }
        isMeetFood(this,food);
    }
    //检测是否撞到食物
    function isMeetFood(snake,food){
        var head =snake.bodys[0];
        if(head.x === food.x && head.y ===food.y){
            food.render();
            var lastBody = snake.bodys[snake.bodys.length - 1];
            snake.bodys.push({x:lastBody.x,y:lastBody.y,color:'yellow'});
        }
    }
    window.Snake = Snake;
}())